/**
 * Created by MetaLab_K on 2016/3/26.
 */
angular.module('metalabPartnerApp').controller('ProjectCooperateCtrl', ['$rootScope', '$scope', '$stateParams', 'MetaResources', '$state', 'MetaRemind', 'MetaConstants', '$timeout', '$uibModal',
    function ($rootScope, $scope, $stateParams, resource, $state, MetaRemind, constants, $timeout, $uibModal) {

        $scope.processStates = constants.ProcessStates;//状态对应的静态值

        $scope.page = {//数据模板
            currentPage: 0,
            pageNumber: 5,
            total: 0,
            data: []
        };
        $scope.remarkForm = {//备忘信息数据模型
            tag: '',
            content: '',
            solutionProcessId: 0
        };
        $scope.remarks = [];//备忘信息集合
        $scope.bankForm = {//银行账户表单
            bankAccount: '',
            bank: '',
            applyForReimbursementAt: '',
            msg: ''
        };
        $scope.starForm = {//评价表单
            starToDemandProvider: 0,
            starToProjectLeader: 0,
            starToPlatform: 0,
            confirmContractAt: ''
        };

        /**
         * @function 联系合伙人
         * 进入联系沟通状态，在合伙人点击邀请对接后，激活同意对接按钮
         */

        $scope.getContactNumber = function (solutionProcess) {
            resource.process.technologyProcessUpdate({
                id: solutionProcess.technologySideProcess.id,
                _embed: 'SolutionProcess'
            }, {
                checkDemandSideAt: (new Date())
            }, function (data) {
                console.log('联系合伙人:', solutionProcess.state);
                $scope.contacted = true;
                solutionProcess.technologySideProcess.checkDemandSideAt = data.checkDemandSideAt;
                solutionProcess.state = data.solutionProcess.state;
                $scope.addRemark('联系项目负责人', data.solutionProcess);
                console.log('联系合伙人:', solutionProcess.state);
            }, function (err) {
                MetaRemind.error("出错啦", err)
            });

        };

        /**
         * @function 同意线下对接
         * 进入线下对接状态
         */
        $scope.agreeOfflineMeeting = function (solutionProcess) {
            resource.process.technologyProcessUpdate({
                id: solutionProcess.technologySideProcess.id,
                _embed: 'SolutionProcess'
            }, {
                agreeWithInvitingAt: (new Date())
            }, function (data) {
                console.log('同意线下对接:', solutionProcess.state);
                solutionProcess.technologySideProcess.agreeWithInvitingAt = data.agreeWithInvitingAt;
                solutionProcess.state = data.solutionProcess.state;
                $scope.addRemark('我同意进行线下对接，诚意金将可用于线下开销', solutionProcess);
                console.log('同意线下对接:', solutionProcess.state);
            }, function (err) {
                MetaRemind.error("出错啦", err)
            });
        };
        /**
         * @function 提交银行账户
         * 提交银行账户准备接受诚意金
         */
        $scope.beforeOfflineMeeting = function (solutionProcess) {
            $scope.bankForm.msg=null;
            if (isNaN($scope.bankForm.bankAccount)) {
                $scope.bankForm.msg = "请重新确认账号信息！";
                return;
            }
            $scope.bankForm.applyForReimbursementAt = new Date();
            resource.process.technologyProcessUpdate({
                id: solutionProcess.technologySideProcess.id,
                _embed: 'SolutionProcess'
            }, $scope.bankForm, function (data) {
                solutionProcess.technologySideProcess.applyForReimbursementAt = data.applyForReimbursementAt;
                solutionProcess.technologySideProcess.bankAccount = data.bankAccount;
                solutionProcess.technologySideProcess.bank = data.bank;
                solutionProcess.state = data.solutionProcess.state;
            }, function (err) {
                MetaRemind.error("出错啦", err);
            });
        };
        /**
         * @function 签订合同
         * 在需求方负责人上传合同后，才能被触发
         */
        $scope.confirmContract = function (solutionProcess) {
            console.log($scope.starForm);
            if ($scope.starForm.starToDemandProvider < 1 || $scope.starForm.starToPlatform < 1 || $scope.starForm.starToProjectLeader < 1) {
                $scope.starFormError = true;
                return;
            }
            $scope.starFormError = false;
            $scope.starForm.confirmContractAt = new Date();
            resource.process.technologyProcessUpdate({
                id: solutionProcess.technologySideProcess.id,
                _embed: 'SolutionProcess'
            }, $scope.starForm, function (data) {
                console.log('签订合同:', solutionProcess.state);
                solutionProcess.technologySideProcess.confirmContractAt = data.confirmContractAt;
                solutionProcess.showMask = true;
                $timeout(function () {
                    console.log('before', solutionProcess.state);
                    solutionProcess.state = data.solutionProcess.state;
                    solutionProcess.showMask = false;
                    console.log('after', solutionProcess.state);
                }, 3000);
                $scope.addRemark('对接成功，合同已签订', solutionProcess);
                console.log('签订合同:', solutionProcess.state);
            }, function (err) {
                MetaRemind.error("出错啦", err);
            });
        };

        /**
         * @function 添加备注
         */
        $scope.addRemark = function (content, solutionProcess) {
            $scope.remarkForm.tag = Object.keys($scope.processStates)[solutionProcess.state];
            $scope.remarkForm.content = content ? content : $scope.remarkForm.content;
            $scope.remarkForm.solutionProcessId = solutionProcess.id;
            resource.note.add({
                userId: '_self'
            }, $scope.remarkForm, function (data) {
                // MetaRemind.success("添加成功！");
                getRemark(solutionProcess);
                $scope.remarkForm.content = '';
            }, function (err) {
                // MetaRemind.error("添加失败！");
            });
        };
        /**
         * @function 删除备注
         * @param index 索引
         */
        $scope.deleteRemark = function (remarkId, solutionProcessId) {
            resource.note.delete({
                id: remarkId
            }, function (data) {
                MetaRemind.success("删除成功！");
                getRemark(solutionProcessId);
            }, function (err) {
                MetaRemind.error("删除失败！");
            });
        };
        /**
         * @function 查看进程的备注
         * @param solutionProcessId 进程id
         */
        var getRemark = function (solutionProcess) {
            resource.note.get({
                userId: '_self',
                solutionProcessId: solutionProcess.id,
                _sort: '-updatedAt'
            }, function (data) {
                solutionProcess.remarks = data;
            }, function (err) {
                MetaRemind.error("出错啦！", err);
            });
        };

        /**
         * @function 拒绝方案
         */
        $scope.reject = function (solutionProcess) {
            var modalInstance = $uibModal.open({
                animation: false,
                templateUrl: 'views/project/common/projectRejectModal.html',
                controller: ['$scope', '$uibModalInstance', function ($scope, $uibModalInstance) {
                    $scope.reason = '';
                    $scope.cancel = function () {
                        $uibModalInstance.dismiss('cancel');
                    };
                    $scope.ok = function () {
                        $uibModalInstance.close($scope.reason);
                    };
                }],
                size: 'md'
            });
            modalInstance.result.then(function (str) {
                resource.process.technologyProcessUpdate({
                    id: solutionProcess.technologySideProcess.id,
                    _embed: 'solutionProcess'
                }, {
                    causeForCancel: str
                }, function (data) {
                    console.log("reject data:", data);
                    solutionProcess.canceled = data.solutionProcess.canceled;
                }, function (err) {
                    MetaRemind.error("出错啦", err)
                });
            }, function () {
            });
        };

        /**
         * @function 始终有一个打开
         * @param $event 点击事件
         * @param scope 当前作用域
         */
        $scope.metaToggleOpen = function ($event, scope) {
            if (!$event.target.parentNode.parentNode.parentNode.parentNode.parentNode.classList.contains('panel-open')) {
                scope.toggleOpen();
            }
        };

        $scope.page.data = $scope.$parent.datas.cooperate;
        console.log($scope.$parent.datas);
    }]);
